package com.dimao.certificate_build_service;

import com.dimao.certificate_build_service.Util.Log.Level;
import com.dimao.certificate_build_service.Util.Log.Log;
import com.dimao.certificate_build_service.Util.Log.SaveMode;
import com.dimao.certificate_build_service.http.ApiBridgeFactory;
import com.dimao.certificate_build_service.pdf.PDFConfig;
import com.dimao.certificate_build_service.pdf.kotiln.PDFBuildQueue;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;

public class BuildService extends AbstractVerticle {
    private HttpServer httpServer;

    public static void main(String[] args){
        Vertx vertx = Vertx.vertx();
        Log.initLogger(vertx, SaveMode.Text, Level.warn);
        PDFConfig.loadInFile(vertx, "PdfConfig.json")
                .compose(pdfConfig ->
                        PDFBuildQueue.init("BuildService/PDFBuildQueue", vertx, pdfConfig)
                )
                .setHandler(result -> {
                    if(result.failed())
                        Log.error("start build service failed", result.cause());
                    else vertx.deployVerticle(
                            "com.dimao.certificate_build_service.BuildService",
                            new DeploymentOptions()
                                    .setInstances(2)
                                    .setWorkerPoolSize(10)
                    );
                });
    }

    @Override
    public void start() throws Exception {
        HttpServerOptions options = new HttpServerOptions();
//                .setSsl(true)
//                .setKeyStoreOptions(new JksOptions())
//                .setKeyCertOptions(new PemKeyCertOptions()
//                        .setCertPath("security/synu.timkj.com_bundle.crt")
//                        .setKeyPath("security/synu.timkj.com.key"));
        httpServer = vertx.createHttpServer(options);
        Router router = Router.router(vertx);

        router.route().handler(BodyHandler.create());
        router.post("/pdf/queue/add").handler(ApiBridgeFactory.produceAddToPDFBuildQueueApi());
        router.post("/pdf/merge").handler(ApiBridgeFactory.produceGetMultpleTemporaryPDFApi());
        router.post("/pdf/get").handler(ApiBridgeFactory.produceShowSinglePDFApi());

        httpServer.requestHandler(router).listen(10000);
    }

    @Override
    public void stop() throws Exception {
        httpServer.close();
    }
}
